/**
 * 项目名称: Topic_106.cpp
 * 项目路径: study/DataStructure/LeetCode/树/中等
 * 编辑时间: 2024年08月16日08时09分09秒
 * 用   户: 轻尘
 */

#include <bits/stdc++.h>

using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;

    TreeNode() : val(0), left(nullptr), right(nullptr) {}

    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}

    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    unordered_map<int,int>map;
    TreeNode* build(vector<int>& inorder, vector<int>& postorder,int il,int ir,int pl,int pr){
        if(pl>pr)return nullptr;
        int node = postorder[pr];
        TreeNode * root = new TreeNode;
        root->val = node;

        int mid = map[root->val];
        //递归遍历左子树
        root->left = build(inorder,postorder,il,mid-1,pl,pl+mid-1-il);
        //递归遍历右子树
        root->right = build(inorder,postorder,mid+1,ir,pl+mid-1-il+1,pr-1);
        return root;
    }
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        if(inorder.empty())return nullptr;
        for(int i =0;i<inorder.size();i++)
            map[inorder[i]]=i;
        return build(inorder,postorder,0,inorder.size()-1,0,postorder.size()-1);
    }
};